<?php

namespace App\Providers;

use App\Models\CommentDetail;
use App\Models\Topic;
use App\Observers\TopicObserver;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Pagination\Paginator;
use App\Models\AttachmentRelationship;
use App\Models\Comment;
use App\Models\User;
use App\Observers\CommentDetailObserver;
use App\Observers\UserObserver;


class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        \Carbon\Carbon::setLocale('zh');//设置Carbon使用中文
        \Illuminate\Support\Facades\Schema::defaultStringLength(191);//应该限制索引长度，不应该限制字符长度。坑爹这里不支持设置索引长度
        DB::connection()->enableQueryLog();

        //记录sql语句
//        $this->logSql();
        
        //自定义验证规则
        $this->customValidateRule();

        $this->initCloudinary();

        $this->observeEloquentEvent();

    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(\Faker\Generator::class, function() {
            return \Faker\Factory::create('zh_CN');
        });
    }
    
    /**
     * 手工记录sql
     */
    private function logSql()
    {
        \DB::listen(function($query) {
            $log = sprintf(
                "%s, sql: %s, bindngs: %s, timeuse: %sms %s",
                date('Y-m-d H:i:s'),
                $query->sql,
                json_encode($query->bindings, 320),
                $query->time,
                PHP_EOL
            );
            file_put_contents(sprintf('%s/sql-%s.log', storage_path('logs'), date('Ymd')), $log, FILE_APPEND);
        });
    }
    
    private function customValidateRule()
    {
        \Validator::extend('attachment', function ($attribute, $value, $parameters, $validator) {
            return filter_var($value, FILTER_VALIDATE_URL) && strpos($value, config('filesystems.disks.qiniu.domains.default')) !== false;
        }, ':attribute 不是有效图片地址');
    }

    private function initCloudinary()
    {
        $driver = config('admin.upload.disk');
        $config = config('filesystems.disks.' . $driver);
        \Cloudinary::config(array(
            "cloud_name" => $config['cloud_name'],
            "api_key" => $config['api_key'],
            "api_secret" => $config['api_secret'],
        ));
    }

    private function observeEloquentEvent()
    {
        Topic::observe(TopicObserver::class);
    }

}
